package com.szty.libarytest.launcher

import android.content.ComponentName
import android.content.Intent
import android.content.pm.ResolveInfo
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import androidx.recyclerview.widget.GridLayoutManager
import com.szty.libarytest.R
import kotlinx.android.synthetic.main.activity_launcher.*

class LauncherActivity : AppCompatActivity(),MyAppsAdapter.MyAppsAdapterSetOnClickListener {
    private val mMApps = arrayListOf<ResolveInfo>()
    private val mMyAppsAdapter by lazy {
        MyAppsAdapter(this, mMApps)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launcher)
        getApps()
        setData()
    }

    private fun setData() {
        rv_app_list.apply {
            layoutManager = GridLayoutManager(this@LauncherActivity,4)
            adapter = mMyAppsAdapter
            mMyAppsAdapter.setMyAppsAdapterSetOnClickListener(this@LauncherActivity)
        }
    }

    private fun getApps() {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        mMApps.addAll(packageManager.queryIntentActivities(intent, 0))

    }

    override fun OnClickListener(i: Int) {
        val resolveInfo = mMApps[i]
        val packageName = resolveInfo.activityInfo.packageName
        val name = resolveInfo.activityInfo.name
        val componentName = ComponentName(packageName, name)
        val intent = Intent()
        intent.component = componentName
        startActivity(intent)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return true
    }
}